﻿<?php
	//function that creates a menu-list
	function createList($page, &$db) {
		$page = safety(getTopPage($db, $page, false));
		$pageQuery = mysqli_query($db, "SELECT id, name, tagName, parentId, isLink FROM pages WHERE parentId='NULL'");
		if (session_status() == PHP_SESSION_NONE) {
			session_start();
		}
		createListRecursive($pageQuery, $db, -1, 0);
	}

	//help-function that go through the DB page for page with recursion
	function createListRecursive(&$pageQuery, &$db, $depth, $rights) {
		//so we know the depth of the tree
		++$depth;
		//while we have a page to check
		while($page = $pageQuery->fetch_assoc()) {
			//SQL query that JOINS two DB to get the rights for a specific page for a single user
			$rightsQuery = mysqli_query($db, "SELECT rights FROM group_rights JOIN users ON group_rights.groupId = users.rightsId WHERE group_rights.pageId = '".$page["id"]."' AND users.username = '".$_SESSION["username"]."' LIMIT 1");	
			$right = $rightsQuery->fetch_assoc();
			if($rights !== null) {
				$rights |= $right["rights"];
				//echo $rights;
			}
			//if we are at start we do not want to print anything or we do not have the rights
			if($depth === 0 || $rights <= 1) {
				//do nothing
			}else if($page["isLink"] == 0) { //if we do not have a link, show toggler
				echo "<li>";
				echo "<label label-default=\"\" class=\"tree-toggler nav-header\">".$page["tagName"]."</label>";
				echo "<ul class=\"nav  tree active-trial\">";
			}else{ //else we have a link
				echo "<li><a class=\"menuAjaxLink\" href=\"home.php?page=".$page["id"]."\">".$page["tagName"]."</a>";
			}
			
			//get the id of this nde
			$parent = $page["id"];
			//get all the children from this node
			$nextPageQuery = mysqli_query($db, "SELECT id, name, tagName, parentId, isLink FROM pages WHERE parentId='$parent'");
			//call the same function with the query of its children
			createListRecursive($nextPageQuery, $db, $depth, $rights);
	
			//hide if no rights
			if($rights > 1) {
		
				//if we are above 0 depth
				if($depth > 0) {
					//if we do not have a link add a extra </ul>
					if($page["isLink"] == 0) {
						echo "</ul>";
					}
					echo "</li>";
				}
			
				//in case of depth 1 we want a divider between them.
				if($depth === 1){
					echo "<li class=\"nav-divider\"></li>";
				}
			}
		}
	}
?>